﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using Kiiro.Model;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;

namespace Kiiro.WebServices
{

    [Serializable]
    public class KiiroDiscussionStatusFlags
    {
        public bool ProjectDoesNotExist = false;
        public bool UserDoesNotExist = false;
        public bool ExceptionOccurred = false;
        public string Exception;
        public bool Success = false;
    }

    /// <summary>
    /// Summary description for KiiroDiscussion
    /// </summary>
    [WebService(Namespace = "http://mykiiro.com/discussion")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class KiiroDiscussion : System.Web.Services.WebService
    {

        [WebMethod]
        public void CreateDiscussion(string projectSiteName, string title, string body, DateTime createdDate, int createdBySPUserID, string[] attachmentSessionKeys, string [] attachmentFileNames, out int discussionID, out KiiroDiscussionStatusFlags status)
        {
            Guid siteCollectionId;
            string serverRelativeUrl = null;
            status = new KiiroDiscussionStatusFlags();
            status.Success = true;            
            Discussion discussion = null;
            User createdBy = null;
            discussionID = 0;

            try
            {
                //try and get the site collection ID and relative URL
                SPHelpers.GetSiteCollectionIdAndServerRelativeUrl(Context.Request.Url.Scheme + "://" + Context.Request.Url.Authority + Context.Request.RawUrl, out siteCollectionId, out serverRelativeUrl);

                //check that the project url exists
                if (!WebServicesHelper.DoesProjectExist(projectSiteName, siteCollectionId, serverRelativeUrl))
                {
                    status.ProjectDoesNotExist = true;
                    status.Success = false;
                }
                else
                {
                  
                    //get the created by
                    createdBy = UserModel.GetOrCreateUser(createdBySPUserID, siteCollectionId, serverRelativeUrl + "/" + projectSiteName);

                    
                    discussion = new Discussion();
                    if (title.Length > 255)
                        title = title.Substring(0, 255);
                    discussion.Title = title;
                    if (body.Length > 5000)
                        body = body.Substring(0, 5000);
                    discussion.Text = body;
                    discussion.CreatedBy = createdBy;                    
                    discussion.CreatedDate = createdDate;
                    discussion.ModifiedBy = createdBy;
                    discussion.ModifiedDate = createdDate;
                    discussion.EditType = EditType.Created;

                    discussion.AttachmentList = GetAttachmentsFromSessions(attachmentSessionKeys, attachmentFileNames, createdBy, createdDate);
                    
                    discussion = DiscussionModel.Save(discussion, siteCollectionId, serverRelativeUrl + "/" + projectSiteName);
                    discussionID = discussion.Id;
                                                                       
                }
            }
            catch (Exception ex)
            {
                status.ExceptionOccurred = true;
                status.Exception = ex.ToString();
                status.Success = false;
            }
            
        }

        [WebMethod]
        public void AddCommentToDiscussion(string projectSiteName, int discussionID, string commentBody, DateTime createdDate, int createdBySPUserID, string[] attachmentSessionKeys, string[] attachmentFileNames, out KiiroDiscussionStatusFlags status)
        {
            Guid siteCollectionId;
            string serverRelativeUrl = null;
            status = new KiiroDiscussionStatusFlags();
            status.Success = true;
            Discussion discussion = null;
            Comment comment = null;
            User createdBy = null;            

            try
            {
                //try and get the site collection ID and relative URL
                SPHelpers.GetSiteCollectionIdAndServerRelativeUrl(Context.Request.Url.Scheme + "://" + Context.Request.Url.Authority + Context.Request.RawUrl, out siteCollectionId, out serverRelativeUrl);

                //check that the project url exists                
                if (!WebServicesHelper.DoesProjectExist(projectSiteName, siteCollectionId, serverRelativeUrl))
                {
                    status.ProjectDoesNotExist = true;
                    status.Success = false;
                }
                else
                {

                    //get the created by
                    createdBy = UserModel.GetOrCreateUser(createdBySPUserID, siteCollectionId, serverRelativeUrl + "/" + projectSiteName);

                    comment = new Comment();
                    comment.Text = commentBody;
                    comment.CreatedBy = createdBy;
                    comment.CreatedDate = createdDate;
                    comment.ModifiedBy = createdBy;
                    comment.ModifiedDate = createdDate;
                    comment.EditType = EditType.Created;
                    comment.DiscussionId = discussionID;
                
                    comment.AttachmentList = GetAttachmentsFromSessions(attachmentSessionKeys, attachmentFileNames, createdBy, createdDate);

                    comment = CommentModel.Save(comment, siteCollectionId, serverRelativeUrl + "/" + projectSiteName);

                }
            }
            catch (Exception ex)
            {
                status.ExceptionOccurred = true;
                status.Exception = ex.ToString();
                status.Success = false;
            }

        }

        private List<Attachment> GetAttachmentsFromSessions(string[] attachmentSessionKeys, string[] attachmentFileNames, User createdBy, DateTime createdDate)
        {
            List<Attachment> attachments = new List<Attachment>();

            
            //add on the attachments
            if (attachmentSessionKeys != null)
            {
                int i = 0;
                byte[] fileBytes = null;
                Attachment attachment = null;
                KiiroDocument doc = new KiiroDocument();
                foreach (string sessionKey in attachmentSessionKeys)
                {
                    fileBytes = doc.ReadSessionFile(sessionKey);
                    doc.DeleteSessionFile(sessionKey);
                    attachment = new Attachment();
                    attachment.CreatedBy = createdBy;
                    attachment.CreatedBy = createdBy;
                    attachment.CreatedDate = createdDate;
                    attachment.ModifiedBy = createdBy;
                    attachment.ModifiedDate = createdDate;
                    attachment.EditType = EditType.Created;
                    attachment.Bytes = fileBytes;
                    attachment.FileName = attachmentFileNames[i];
                    attachments.Add(attachment);
                    ++i;
                }
            }
            return attachments;
        }
    }


}
